use jsonwebtoken::{encode, decode, Header, Algorithm, EncodingKey, DecodingKey, Validation};
use serde::{Deserialize, Serialize};

const JWT_SECRET: &[u8] = b"secret";

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    sub: String,  // 主题
    exp: usize,  // 到期时间
}

// 生成 JWT
pub(crate) fn create_jwt(username: &str) -> Result<String, jsonwebtoken::errors::Error> {
    let expiration = chrono::Utc::now()
        .checked_add_signed(chrono::Duration::minutes(60))
        .expect("有效时间点计算失败")
        .timestamp();

    let claims = Claims {
        sub: username.to_owned(),
        exp: expiration as usize,
    };
    encode(&Header::default(), &claims, &EncodingKey::from_secret(JWT_SECRET))
}

// 验证 JWT
pub(crate) fn validate_jwt(token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
    decode::<Claims>(
        token,
        &DecodingKey::from_secret(JWT_SECRET),
        &Validation::new(Algorithm::HS256),
    )
        .map(|data| data.claims)
}